// router/index.js
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import {
  IconHome,
  IconApps,
  IconStorage,
  IconSettings,
} from '@arco-design/web-vue/es/icon';
import {CacheApp, LocalStorage} from "@/utils/cache.ts";

export const menuRoutes = [
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/page/dashboard/index.vue'),
    meta: {
      hideInMenu: false,
      title: '仪表盘',
      icon: IconHome,
      tooltip: '仪表盘'
    }
  },
  {
    path: '/apps',
    name: 'Apps',
    component: () => import('@/views/page/apps/index.vue'),
    meta: {
      hideInMenu: false,
      title: '应用管理',
      icon: IconApps,
      tooltip: '应用管理'
    }
  },
  {
    path: '/repos',
    name: 'Repos',
    component: () => import('@/views/page/repos/index.vue'),
    meta: {
      hideInMenu: false,
      title: '仓库管理',
      icon: IconStorage,
      tooltip: '仓库管理'
    }
  },
  {
    path: '/settings',
    name: 'Settings',
    component: () => import('@/views/page/settings/index.vue'),
    meta: {
      hideInMenu: false,
      title: '系统设置',
      icon: IconSettings,
      tooltip: '系统设置'
    }
  }
];

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/dashboard',
    component: () => import('@/views/main/Home.vue'),
    children: menuRoutes
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 获取缓存数据
let store: Array<CacheApp> = new LocalStorage('get').store;
/**
 * @function beforeEach
 * @description 路由拦截, 获取缓存数据, 判断应用列表是否为空, 且app.selected为true的元素, 如果有, 则进入仓库管理页面, 否则进入主页面
 */
router.beforeEach((_to, from, next) => {
  if (from.path === '/') {
    // 判断应用列表是否为空, 且app.selected为true的元素
    if (store.length > 0 ){
      const app: Array<CacheApp> = store.filter((app: CacheApp) => app.selected);
      store = [] // 清空缓存数据, 避免下次进入页面时, 循环获取数据, 一次性使用
      if (app.length > 0 ) {
        return next({ name: 'Repos', query: { appId: app[0].id} });
      }
    }
  }
  next();
})

export default router;
